package com.tupu.service.impl.dispatch;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tupu.common.PageResult;
import com.tupu.entity.dispatch.StandardizationDeviceStandard;
import com.tupu.entity.dispatch.StandardizationNameStandard;
import com.tupu.entity.dispatch.StandardizationPoint;
import com.tupu.entity.dispatch.StandardizationRule;
import com.tupu.entity.dto.PointDO;
import com.tupu.entity.dto.StandardizationPointDTO;
import com.tupu.entity.dto.T0007PointDTO;
import com.tupu.entity.ocs.T0003Station;
import com.tupu.entity.ocs.T1211Device;
import com.tupu.entity.ocs.T1216Devicetype;
import com.tupu.mapper.dispatch.StandardizationDeviceStandardMapper;
import com.tupu.mapper.dispatch.StandardizationNameStandardMapper;
import com.tupu.mapper.ocs.T0003StationMapper;
import com.tupu.mapper.ocs.T0007PointMapper;
import com.tupu.mapper.ocs.T1211DeviceMapper;
import com.tupu.mapper.ocs.T1216DevicetypeMapper;
import com.tupu.service.dispatch.StandardizationPointService;
import com.tupu.mapper.dispatch.StandardizationPointMapper;
import com.tupu.service.dispatch.StandardizationRuleService;
import com.tupu.util.EditDistance;
import com.tupu.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author 15702
 * @description 针对表【tb_standardization_point】的数据库操作Service实现
 * @createDate 2023-11-10 10:56:58
 */
@Slf4j
@Service
public class StandardizationPointServiceImpl extends ServiceImpl<StandardizationPointMapper, StandardizationPoint> implements StandardizationPointService {

    @Autowired
    private T0007PointMapper t0007PointMapper;

    @Autowired(required = false)
    private T0003StationMapper t0003StationMapper;

    @Autowired(required = false)
    private T1211DeviceMapper t1211DeviceMapper;

    @Autowired(required = false)
    private T1216DevicetypeMapper t1216DevicetypeMapper;

    @Autowired
    private StandardizationRuleService standardizationRuleService;

    @Autowired(required = false)
    private StandardizationDeviceStandardMapper standardizationDeviceStandardMapper;

    @Autowired(required = false)
    private StandardizationNameStandardMapper standardizationNameStandardMapper;

    @Autowired(required = false)
    private StandardizationPointMapper standardizationPointMapper;

    @Value("${file.pythonAddress}")
    private String url;

    @Override
    public Page<StandardizationPoint> pointSignalPage(String station, String pointName, String validResult, Long page, Long size) {
        QueryWrapper<StandardizationPoint> queryWrapper = new QueryWrapper<>();
        Page<StandardizationPoint> info = new Page<>(page, size);
        if (StringUtils.isNotEmpty(station)) {
            queryWrapper.eq("station", station);
        }
        if (StringUtils.isNotEmpty(pointName)) {
            queryWrapper.like("point_name", pointName);
        }
        if (StringUtils.isNotEmpty(validResult)) {
            queryWrapper.eq("valid_result", validResult.equals("合格") ? 1 : 0);
        }
        queryWrapper.orderByDesc("record_time");
        baseMapper.selectPage(info, queryWrapper);
        List<StandardizationPoint> records = info.getRecords();
        for (StandardizationPoint point : records) {
            Integer standardId = point.getStandardId();
            if (null != standardId) {
                StandardizationDeviceStandard standard = standardizationDeviceStandardMapper.selectById(standardId);
                point.setStandardName(standard.getStandardName());
                point.setStandardDesc(standard.getStandardDesc());
            }
        }
        return info;
    }

    @Override
    public void validPointData(LocalDateTime startTime, LocalDateTime endTime) {
        Duration duration = Duration.between(startTime, endTime);
        long days = duration.toDays();
        if (days > 5) {
            for (long i = 0; i < days; i++) {
                LocalDateTime startTime1 = startTime.plusDays(i);
                LocalDateTime endTime1 = startTime.plusDays(i + 1);
                log.info("分批计算标准化 startTime:{} endTime:{}", startTime1, endTime1);
                this.doValidPointData(startTime1, endTime1);
            }
        } else {
            this.doValidPointData(startTime, endTime);
        }
    }

    public void doValidPointData(LocalDateTime startTime, LocalDateTime endTime) {
        // 每次计算清空缓存
        standardizationRuleService.clearRuleCache();
        List<T0007PointDTO> list = t0007PointMapper.findT0007Point(startTime.toEpochSecond(ZoneOffset.of("+8")), endTime.toEpochSecond(ZoneOffset.of("+8")));
        list.forEach(item -> {
            StandardizationPoint standardizationPoint = null;
            try {
                standardizationPoint = this.validItem(item);
            } catch (IllegalAccessException e) {
                log.error(e.toString());
            }
            try {
                this.baseMapper.insert(standardizationPoint);
            } catch (DuplicateKeyException e) {
                this.baseMapper.updateById(standardizationPoint);
            }
        });
    }

    public StandardizationPoint validItem(T0007PointDTO item) throws IllegalAccessException {
        /**
         * 情况一：设备名称规范，  设备动作规范；        校验规则：规范规则；            结果：合格。
         * 情况二：设备名称规范，  设备动作不规范；      校验规则：规范规则；            结果：不合格。
         * 情况三：设备名称规范，  没有对应设备动作规范；校验规则：设备名称，无对应规范，结果：无对应规范。
         * 情况四：设备名称不规范，设备动作规范；        校验规则：规范规则；            结果：不合格。
         * 情况五：设备名称不规范，设备动作不规范；      校验规则：规范规则；            结果：不合格。
         * 情况六：设备名称不规范，没有对应设备动作规范；校验规则：设备名称，无对应规范；结果：不合格。
         */
        StandardizationPoint standardizationPoint = new StandardizationPoint();
        standardizationPoint.setProblemId(item.getC0007PointId());
        standardizationPoint.setStation(item.getC0003StationDesc());
        standardizationPoint.setStationNo(item.getC0003StationNo());
        standardizationPoint.setDeviceName(item.getC1211DEVDESC());
        standardizationPoint.setDeviceId(item.getC1211DevId());
        standardizationPoint.setDeviceType(item.getC1216DEVTYPEDESC());
        standardizationPoint.setDeviceTypeCode(item.getC1216DEVTYPE());
        standardizationPoint.setPointName(item.getC0007PointDesc());
        standardizationPoint.setMessageType(item.getMessageType());

        String pointDesc = item.getC0007PointDesc();
        RestTemplate restTemplate = new RestTemplate();
        // 发送 POST 请求
        Map<String, Object> requestBody = new HashMap<>();
        //requestBody.put("query", "220KV母线变压器闭合");
        requestBody.put("query", pointDesc);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 将请求体转换成字符串形式
        String jsonBody = JSONObject.toJSONString(requestBody);
        HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);
        ResponseEntity<Object> entity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Object.class);
        Object body = entity.getBody();
        //获取属性名
        Field[] fields = body.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String value = field.get(body).toString();
            if (value.contains("result")) {
                String[] keyValuePairs = value.substring(value.indexOf("{") + 1, value.indexOf("}")).split(", ");
                Map<String, String> keyValueMap = new HashMap<>();
                for (String pair : keyValuePairs) {
                    String[] splitPair = pair.split("=");
                    keyValueMap.put(splitPair[0].trim(), splitPair[1].trim());
                }
                String checkRule = keyValueMap.get("check_rule");
                String deviceName = keyValueMap.get("device_name");
                String infoName = keyValueMap.get("info_name");
                Double proba = Double.valueOf(keyValueMap.get("proba"));
                String standardAction = keyValueMap.get("standard_action");
                String standardDesc = keyValueMap.get("standard_desc");
                String standardId = keyValueMap.get("standard_id");
                String standardName = keyValueMap.get("standard_name");
                Integer stationMerge = Integer.valueOf(keyValueMap.get("station_merge"));
                //point.setDeviceName(deviceName);
                QueryWrapper<T1211Device> wrapper = new QueryWrapper<>();
                wrapper.eq("C1211_DEVDESC", deviceName);
                T1211Device deviceOne = t1211DeviceMapper.selectOne(wrapper);
                if (null != deviceOne) {
                    standardizationPoint.setDeviceId(deviceOne.getC1211DEVID());
                    String devtype = deviceOne.getC1216DEVTYPE();
                    QueryWrapper<T1216Devicetype> wrapper2 = new QueryWrapper<>();
                    wrapper2.eq("C1216_DEVTYPE", devtype);
                    T1216Devicetype t1216Devicetype = t1216DevicetypeMapper.selectOne(wrapper2);
                    standardizationPoint.setDeviceType(t1216Devicetype.getC1216Devtypedesc());
                }
                standardizationPoint.setInformationType(infoName);
                standardizationPoint.setActionName(standardAction);
                standardizationPoint.setCheckRules(checkRule);
                standardizationPoint.setSimilarity(proba);
                if (proba > 0.8) {
                    standardizationPoint.setValidResult(1);
                    standardizationPoint.setValidResultStr("合格");
                } else {
                    standardizationPoint.setValidResult(0);
                    standardizationPoint.setValidResultStr("不合格");
                }
                standardizationPoint.setMainMerge(stationMerge);
                standardizationPoint.setStandardId(Integer.valueOf(standardId));
                standardizationPoint.setStandardDesc(standardDesc);
                standardizationPoint.setStandardName(standardName);
                standardizationPoint.setInformationType(infoName);
            }
        }
/*        // \d+?kV
        String str = item.getC0007PointDesc();
        String pattern = "\\d+?kV";

        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(str);
        System.out.println(m.matches());
        List<StandardizationRule> ruleList = standardizationRuleService.getRuleCache(item.getC0015VOLTAGELEVELDESC(), item.getC1216DEVTYPEDESC());
        // 提取action规则
        String deviceName = Optional.ofNullable(item.getC1211DEVDESC()).orElse("");
        String deviceNamePre = EditDistance.textSubStr(item.getC0007PointDesc(), deviceName);
        String action = Optional.ofNullable(item.getC0007PointDesc()).map(s -> {
            if (item.getC0007PointDesc().contains("手车试验位置")) {
                return "手车试验位置";
            }
            // 使用设备分割
            if ("开关".equals(item.getC1216DEVTYPEDESC()) && item.getC0007PointDesc().endsWith("开关") && item.getC0007PointDesc().equals(item.getC1211DEVDESC())) {
                return s.replaceFirst("(?<=kV).*?(?=开关)", "××");
            } else if (StringUtils.isNotBlank(deviceNamePre) && !deviceNamePre.equals(s)) {
                String[] ss = s.split(deviceNamePre);
                if (ss.length >= 2) {
                    return ss[1];
                } else return null;
            } else {
                String[] ss = s.split("\\S+(F\\d{2,3}[A-Za-z]+\\d?)|\\d+kV\\S+?线\\d+|\\d+kV\\S+?电容器组[A-Z]?\\d+|\\d+开关");
                if (ss.length >= 2) {
                    String a = ss[ss.length - 1].replaceFirst("^[A-Za-z0-9#]+|[0-9#]+", "");
                    return a;
                } else {
                    // 取后6个字符串
                    String a = item.getC0007PointDesc().length() > 6 ? s.substring(item.getC0007PointDesc().length() - 6) : item.getC0007PointDesc();
                    //去除开头的数字字母
                    return a.replaceFirst("^[A-Za-z0-9#]+", "");
                }
            }
        }).orElse("");
        standardizationPoint.setActionName(action);
        Result validRule = getValidRule(item, standardizationPoint, ruleList, action);
        standardizationPoint.setCheckRules(Optional.ofNullable(validRule.rule).map(StandardizationRule::getSpecificationInfoDesc).orElse(null));
        if (validRule.rule == null && (ruleList.size() == 0 || validRule.maxSimilarity.get() <= 0.1d)) {
            validRule = getValidRule(item, standardizationPoint, standardizationRuleService.getRuleCache(null, null), action);
            standardizationPoint.setCheckRules(Optional.ofNullable(validRule.rule).map(StandardizationRule::getSpecificationInfoDesc).orElse(null));
            if (validRule.rule == null) {
                standardizationPoint.setCheckRules("无对应规范");
            }
        }
        standardizationPoint.setSimilarity(Optional.ofNullable(validRule.rule).map(StandardizationRule::getSimilarity).orElse(validRule.maxSimilarity.get()));
        boolean result = true;
        if (StringUtils.isNotEmpty(item.getC0015VOLTAGELEVELDESC())) {
            String v = item.getC0015VOLTAGELEVELDESC().trim();
            // 电压等级和设备信息不符合
            if (item.getC0007PointDesc().contains("kV") && !item.getC0007PointDesc().contains(v)) {
                result = false;
            }
            // 规则包含电压等级，数据不包含则不通过
            if (validRule.rule != null && validRule.rule.getSpecificationInfoDesc().contains("kV") && !item.getC0007PointDesc().contains("kV")) {
                result = false;
            }
//            if (!deviceName.equals(deviceNamePre)) {
//                result = false;
//            }
        }
        // 合格1 不合格0 无对应规范2
        standardizationPoint.setValidResult(result && validRule.rule != null ? 1 : "无对应规范".equals(standardizationPoint.getCheckRules()) ? 2 : 0);
        standardizationPoint.setCheckRules("校验规则：" + ("无对应规范".equals(standardizationPoint.getCheckRules()) ? (deviceName == null ? "" : deviceName + "，") + "无对应规范" : standardizationPoint.getCheckRules()));
        standardizationPoint.setMainMerge(Optional.ofNullable(validRule.rule).map(StandardizationRule::getMainStationMerge).orElse(null));*/

        Integer date = item.getC0007RecordDate();
        if (null != date) {
            Instant instant = Instant.ofEpochSecond(date);
            standardizationPoint.setRecordTime(LocalDateTime.ofInstant(instant, ZoneId.systemDefault()));
        }
        standardizationPoint.setCreateTime(LocalDateTime.now());
        //默认没有训练
        standardizationPoint.setIsTrain(0);
        return standardizationPoint;
    }

    private static Result getValidRule(T0007PointDTO item, StandardizationPoint standardizationPoint, List<StandardizationRule> ruleList, String action) {
        AtomicReference<Double> maxSimilarity = new AtomicReference<>(0d);
        List<StandardizationRule> matchList = StringUtils.isBlank(action) ? new ArrayList<>() : ruleList.stream().filter(r -> {

            String rule = r.getSpecificationInfoDesc();
            String ruleKeyWords = "";
            if ("开关".equals(item.getC1216DEVTYPEDESC()) && item.getC0007PointDesc().endsWith("开关") && item.getC0007PointDesc().equals(item.getC1211DEVDESC())) {
                ruleKeyWords = rule;
            } else if (rule.contains("××")) {

                String[] ss = rule.split("\\S+××(开关|隔离|地刀|刀闸|断路器)");
                if (ss.length >= 2) {
                    ruleKeyWords = ss[1];
                } else {
                    ss = rule.split("××");
                    ruleKeyWords = ss[ss.length - 1];
                    if ("开关".equals(ruleKeyWords) && "开关".equals(item.getC1216DEVTYPEDESC()) && item.getC0007PointDesc().endsWith("开关")) {
                        r.setSimilarity(1d);
                        maxSimilarity.set(1d);
                        return true;
                    }
                }
            } else {
                String[] ss = rule.split("\\S+(母线)");
                if (ss.length >= 2) {
                    ruleKeyWords = ss[1];
                }
            }
            r.setSimilarity(0d);
            if (StringUtils.isBlank(action)) {
                return false;
            }
            String[] ruleKeys = new String[]{""};
            if (ruleKeyWords.contains("/")) {
                ruleKeys = ruleKeyWords.split("/");
            } else {
                ruleKeys = new String[]{ruleKeyWords};
            }
            double similarity = 0d;
            for (int i = 0; i < ruleKeys.length; i++) {
                double similarityI = EditDistance.getsimilarity(action, ruleKeys[i]);
                if (similarityI > similarity) {
                    similarity = similarityI;
                }
            }
            if (similarity > maxSimilarity.get()) {
                maxSimilarity.set(similarity);
            }
            ;
//                        if (Arrays.stream(ruleKeys).anyMatch(k -> k.contains(action))) {
//                            r.setSimilarity(similarity);
//                            return true;
//                        } else

            if (similarity > 0.1d) {
                r.setSimilarity(similarity);
                return true;
            } else {
                return false;
            }
        }).sorted(Comparator.comparing(StandardizationRule::getSimilarity).reversed()).collect(Collectors.toList());
        StandardizationRule rule = matchList.size() > 0 ? matchList.get(0) : null;
        Result result = new Result(maxSimilarity, rule);
        return result;
    }

    private static class Result {
        public final AtomicReference<Double> maxSimilarity;
        public final StandardizationRule rule;

        public Result(AtomicReference<Double> maxSimilarity, StandardizationRule rule) {
            this.maxSimilarity = maxSimilarity;
            this.rule = rule;
        }
    }

    public Map<String, Object> pointTypePercentage(String station, String messageType, String checkResult, LocalDateTime startTime, LocalDateTime endTime) {
        List<Map<String, Object>> list = this.baseMapper.pointTypePercentage(station, messageType, startTime, endTime);
        Map<String, Object> result = list.stream().collect(Collectors.toMap(i -> String.valueOf(i.get("message_type")), i -> i.get("num"), (existing, duplicate) -> duplicate));
        result.putIfAbsent("开关", 0);
        result.putIfAbsent("刀闸", 0);
        result.putIfAbsent("保护信号", 0);
        return result;
    }

    public Map<String, Object> resultPercentage(String station, String messageType, String checkResult, LocalDateTime startTime, LocalDateTime endTime) {
        List<Map<String, Object>> list = this.baseMapper.resultPercentage(station, messageType, startTime, endTime);
        Map<String, Object> result = list.stream().collect(Collectors.toMap(i -> String.valueOf(i.get("result")), i -> i.get("num"), (existing, duplicate) -> duplicate));
        result.putIfAbsent("qualifiedNumber", 0);
        result.putIfAbsent("notQualifiedNumber", 0);
        result.putIfAbsent("total", Optional.ofNullable(result.get("qualifiedNumber")).map(d -> {
            if (d instanceof Integer) {
                return ((Integer) d).longValue();
            } else if (d instanceof Long) {
                return (Long) d;
            }
            return 0L;
        }).orElse(0L) + Optional.ofNullable(result.get("notQualifiedNumber")).map(d -> {
            if (d instanceof Integer) {
                return ((Integer) d).longValue();
            } else if (d instanceof Long) {
                return (Long) d;
            }
            return 0L;
        }).orElse(0L) + Optional.ofNullable(result.get("noRuleNumber")).map(d -> {
            if (d instanceof Integer) {
                return ((Integer) d).longValue();
            } else if (d instanceof Long) {
                return (Long) d;
            }
            return 0L;
        }).orElse(0L));
        if (ObjectUtil.isNotEmpty(result.get("noRuleNumber"))) {
            BigDecimal bigDecimal = new BigDecimal(String.valueOf(result.get("notQualifiedNumber")));
            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(result.get("noRuleNumber")));
            bigDecimal = bigDecimal.add(bigDecimal1).setScale(0);
            result.put("notQualifiedNumber", bigDecimal);
        }
        return result;
    }

    @Override
    public List<String> standardizationDeviceTypeList() {
        return t0007PointMapper.getDeviceTypeList();
    }

    @Override
    public List<String> standardizationStationList(String station) {
        QueryWrapper<T0003Station> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(station)) {
            wrapper.like("C0003_STATION_DESC", "%" + station + "%");
        }
        return t0003StationMapper.selectList(wrapper).stream().map(T0003Station::getC0003StationDesc).collect(Collectors.toList());
    }

    @Override
    public void downloadExcelDemo(HttpServletResponse response) {
        InputStream inputStream = null;
        OutputStream fileOut = null;
        try {
            inputStream = new ClassPathResource("/template/信号标准化模板.xlsx").getInputStream();
            String fileName = new String("信号标准化模板".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setContentType("application/vnd.ms-excel");
            fileOut = response.getOutputStream();
            //循环写入输出流
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                fileOut.write(b, 0, length);
            }
            inputStream.close();
            fileOut.close();
        } catch (Exception e) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            e.printStackTrace();
            throw new RuntimeException("模板下载出错!");
        }
    }

    @Override
    public Map<String, Object> standardizationDeviceImport(MultipartFile file, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        InputStream inputStream;
        StringBuilder message = new StringBuilder();
        List<StandardizationPoint> standardizationPointList = new ArrayList<>();
        try {
            inputStream = file.getInputStream();
            List<PointDO> pointDOS = EasyExcel.read(inputStream).head(PointDO.class).sheet(0).headRowNumber(1).doReadSync();
            if (CollectionUtils.isNotEmpty(pointDOS)) {
                for (PointDO pointDO : pointDOS) {
                    StandardizationPoint point = new StandardizationPoint();
                    Map<String, String> map2 = new HashMap<>();
                    map2.put("station", pointDO.getStation());
                    point.setStation(pointDO.getStation());
                    String pointName = pointDO.getPointName();
                    map2.put("pointName", pointDO.getPointName());
                    point.setPointName(pointDO.getPointName());
                    RestTemplate restTemplate = new RestTemplate();
                    // 发送 POST 请求
                    Map<String, Object> requestBody = new HashMap<>();
                    //requestBody.put("query", "220KV母线变压器闭合");
                    requestBody.put("query", pointName);
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    // 将请求体转换成字符串形式
                    String jsonBody = JSONObject.toJSONString(requestBody);
                    HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);
                    ResponseEntity<Object> entity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Object.class);
                    Object body = entity.getBody();
                    //获取属性名
                    Field[] fields = body.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        field.setAccessible(true);
                        String value = field.get(body).toString();
                        if (value.contains("result")) {
                            String[] keyValuePairs = value.substring(value.indexOf("{") + 1, value.indexOf("}")).split(", ");
                            Map<String, String> keyValueMap = new HashMap<>();
                            for (String pair : keyValuePairs) {
                                String[] splitPair = pair.split("=");
                                keyValueMap.put(splitPair[0].trim(), splitPair[1].trim());
                            }
                            //String deviceType = keyValueMap.get("device_type");
                            //String checkRule = keyValueMap.get("check_rule");
                            String checkRule = keyValueMap.get("standard_desc");
                            String deviceName = keyValueMap.get("device_name");
                            String infoName = keyValueMap.get("info_name");
                            Double proba = Double.valueOf(keyValueMap.get("proba"));
                            String standardAction = keyValueMap.get("standard_action");
                            String standardDesc = keyValueMap.get("standard_desc");
                            String standardId = keyValueMap.get("standard_id");
                            String standardName = keyValueMap.get("standard_name");
                            Integer stationMerge = Integer.valueOf(keyValueMap.get("station_merge"));
                            point.setDeviceName(deviceName);
                            QueryWrapper<T1211Device> wrapper = new QueryWrapper<>();
                            wrapper.eq("C1211_DEVDESC", deviceName);
                            T1211Device deviceOne = t1211DeviceMapper.selectOne(wrapper);
                            if (null != deviceOne) {
                                point.setDeviceId(deviceOne.getC1211DEVID());
                                String devtype = deviceOne.getC1216DEVTYPE();
                                QueryWrapper<T1216Devicetype> wrapper2 = new QueryWrapper<>();
                                wrapper2.eq("C1216_DEVTYPE", devtype);
                                T1216Devicetype t1216Devicetype = t1216DevicetypeMapper.selectOne(wrapper2);
                                point.setDeviceType(t1216Devicetype.getC1216Devtypedesc());
                            }
                            if (!StringUtils.isEmpty(point.getDeviceType())) {
                                point.setDeviceType(infoName);
                            }
                            if (StringUtils.isNotEmpty(infoName)){
                                point.setInformationType(infoName);
                            }
                            if (StringUtils.isNotEmpty(standardAction)){
                                point.setActionName(standardAction);
                            }
                            if (StringUtils.isNotEmpty(checkRule)){
                                point.setCheckRules(checkRule);
                            }
                            if (null != proba){
                                point.setSimilarity(proba);
                            }
                            if (proba > 0.8) {
                                point.setValidResult(1);
                                point.setValidResultStr("合格");
                            } else {
                                point.setValidResult(0);
                                point.setValidResultStr("不合格");
                            }
                            if (null != stationMerge) {
                                point.setMainMerge(stationMerge);
                            }
                            if (!StringUtils.isEmpty(standardId)) {
                                point.setStandardId(Integer.valueOf(standardId));
                            }
                            if (!StringUtils.isEmpty(standardDesc)) {
                                point.setStandardDesc(standardDesc);
                            }
                            if (!StringUtils.isEmpty(standardName)) {
                                point.setStandardName(standardName);
                            }
                        }
                    }
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String time = sdf.format(date);
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    point.setCreateTime(LocalDateTime.parse(time, formatter));
                    point.setIsTrain(1);
                    standardizationPointMapper.insert(point);
                    standardizationPointList.add(point);
                }
            }
            String fileUUid = this.downloadExcelJcjg(standardizationPointList);
            map.put("fileId", fileUUid);
            map.put("pointList", standardizationPointList);
            //map.put("测试", entity.getBody());
            return map;
/*            Map<Integer, T0007PointDTO> devMap = new HashMap<>();
            for (PointDO pointDO : pointDOS) {
                Map<Integer, T0007PointDTO> resultMap = this.t0007PointMapper.getDeviceListByParams(pointDO.getStation(), pointDO.getDeviceType(), pointDO.getDeviceName());
                if (!CollectionUtils.isEmpty(resultMap)) {
                    pointDO.setDeviceId(resultMap.keySet().iterator().next());
                } else {
                    pointDO.setDeviceId(null);
                }
                devMap.putAll(resultMap);
            }
            pointDOS.forEach(item -> {
                StandardizationPoint standardizationPoint = new StandardizationPoint();
                if (ObjectUtil.isNotEmpty(item.getDeviceId())) {
                    T0007PointDTO pointDTO = devMap.get(item.getDeviceId());
                    pointDTO.setC0007PointDesc(item.getPointName());
                    standardizationPoint = this.validItem(pointDTO);
                    if (ObjectUtil.isNotEmpty(standardizationPoint.getValidResult()) && standardizationPoint.getValidResult().equals(1)) {
                        standardizationPoint.setValidResultStr("合格");
                    } else {
                        standardizationPoint.setValidResultStr("不合格");
                    }
                    if (ObjectUtil.isNotEmpty(standardizationPoint.getMainMerge()) && standardizationPoint.getMainMerge().equals(1)) {
                        standardizationPoint.setMainMergeStr("是");
                    } else {
                        standardizationPoint.setMainMergeStr("否");
                    }
                } else {
                    BeanUtils.copyProperties(item, standardizationPoint);
                    standardizationPoint.setValidResultStr("不合格");
                    standardizationPoint.setCheckRules("校验规则：设备名称错误，无对应规范");
                }
                standardizationPointList.add(standardizationPoint);
            });*/
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导入出错! " + e.getMessage());
        }
    }

    @Override
    public void downloadCheckResult(String fileId, HttpServletResponse response) {
        OutputStream fileOut = null;
        InputStream inputStream = null;
        try {
            inputStream = cn.hutool.core.io.FileUtil.getInputStream(System.getProperty("user.dir") + "/templateFile/" + fileId + ".xlsx");
            fileOut = response.getOutputStream();
            String fileName = new String("信号标准化检测结果".getBytes("UTF-8"), "iso-8859-1");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setContentType("application/vnd.ms-excel");
            //循环写入输出流
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                fileOut.write(b, 0, length);
//                downloadedLength += b.length;
            }
            inputStream.close();
            fileOut.close();
        } catch (Exception e) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }

            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }

            e.printStackTrace();
            throw new RuntimeException("模板下载出错!");
        }
    }

    public String downloadExcelJcjg(List<StandardizationPoint> standardizationPointList) {
        HSSFWorkbook wb;
        InputStream inputStream = null;
        try {
            inputStream = new ClassPathResource("/template/信号标准化检测结果下载模板.xlsx").getInputStream();
//            wb = new HSSFWorkbook(inputStream);
            String uuid = UUID.randomUUID().toString();
            String projectPath = System.getProperty("user.dir");

            File file = new File(projectPath + "/templateFile/" + uuid + ".xlsx");
            if (!file.exists()) {
                file.getParentFile().mkdir();
                file.createNewFile();
            }
            EasyExcel.write(file).withTemplate(inputStream).sheet().doFill(standardizationPointList);
            inputStream.close();
            return uuid;
        } catch (Exception e) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            e.printStackTrace();
            throw new RuntimeException("模板下载出错!");
        }
    }

    /**
     * 导出数据
     */
    @Override
    public void exportExcel(HttpServletResponse response, String station, String deviceType, String validResult, LocalDateTime startTime, LocalDateTime endTime) throws IOException {
        QueryWrapper<StandardizationPoint> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(station)) {
            queryWrapper.like("station", station);
        }
        if (StringUtils.isNotEmpty(deviceType)) {
            queryWrapper.eq("message_type", deviceType);
        }
        if (StringUtils.isNotEmpty(validResult)) {
            queryWrapper.eq("valid_result", validResult.equals("合格") ? 1 : 0);
        }
        if (startTime != null) {
            queryWrapper.ge("record_time", startTime);
        }
        if (endTime != null) {
            queryWrapper.le("record_time", endTime);
        }
        queryWrapper.orderByDesc("record_time");
        // 最多导出10w数据
        queryWrapper.last("limit 100000");

        List<StandardizationPoint> pointList = baseMapper.selectList(queryWrapper);
        OutputStream outputStream = response.getOutputStream();
        try {
            FileUtil.setExcelResponseProp(response, "信号标准化结果");
            //这个实现方式非常简单直接，使用EasyExcel的write方法将查询到的数据进行处理，以流的形式写出即可
            EasyExcel.write(outputStream, PointDO.class)//对应的导出实体类
                    .excelType(ExcelTypeEnum.XLSX)//excel文件类型，包括CSV、XLS、XLSX
                    .sheet("信号标准化结果")//导出sheet页名称
                    .doWrite(pointList); //查询获取的数据集合List<T>，转成excel
        } catch (IOException e) {
            log.error(e.toString());
        } finally {
            outputStream.flush();
            outputStream.close();
        }
    }

    @Override
    public List<String> deviceStandardList() {
        List<String> list = new ArrayList<>();
        List<StandardizationDeviceStandard> devices = standardizationDeviceStandardMapper.selectList(null);
        for (StandardizationDeviceStandard device : devices) {
            String name = device.getStandardName();
            list.add(name);
        }
        List<String> deviceList = list.stream().distinct().collect(Collectors.toList());
        return deviceList;
    }

    @Override
    public List<String> deviceDescList(String deviceName) {
        List<String> list = new ArrayList<>();
        QueryWrapper<StandardizationDeviceStandard> wrapper = new QueryWrapper<>();
        wrapper.eq("standard_name", deviceName);
        List<StandardizationDeviceStandard> deviceList = standardizationDeviceStandardMapper.selectList(wrapper);
        for (StandardizationDeviceStandard device : deviceList) {
            String desc = device.getStandardDesc();
            list.add(desc);
        }
        List<String> descList = list.stream().distinct().collect(Collectors.toList());
        return descList;
    }

    @Override
    public PageResult<StandardizationNameStandard> nameDescList(Long page, Long size, String name) {
        PageResult info = new PageResult();
        int totalSize;
        int startIndex = (int) ((page - 1) * size);
        int endIndex;
        List<Map<String, Object>> pageData;
        List<Map<String, Object>> list = standardizationNameStandardMapper.listGroupByMatchWord();
        List<Map<String, Object>> result = new ArrayList<>();
        if (StringUtils.isNotEmpty(name)) {
            for (Map<String, Object> data : list) {
                for (Object value : data.values()) {
                    String stringValue = String.valueOf(value);
                    if (stringValue.contains(name)) {
                        result.add(data);
                        break;
                    }
                }
            }
        }
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(result)) {
            totalSize = result.size();
            endIndex = (int) Math.min(startIndex + size, totalSize);
            pageData = result.subList(startIndex, endIndex);
        } else {
            totalSize = list.size();
            endIndex = (int) Math.min(startIndex + size, totalSize);
            pageData = list.subList(startIndex, endIndex);
        }
        info.setList(pageData);
        info.setTotal((long) totalSize);
        info.setPage(page);
        info.setSize(size);
        info.setTotalPages((totalSize / size + (totalSize % size != 0 ? 1 : 0)));
        return info;
    }

    @Override
    public void addNameDesc(StandardizationNameStandard nameStandard) {
        String enumName = nameStandard.getEnumName();
        String[] names = enumName.split("、");
        String matchWord = nameStandard.getMatchWord();
        for (String name : names) {
            StandardizationNameStandard standard = new StandardizationNameStandard();
            standard.setEnumName(name);
            standard.setMatchWord(matchWord);
            standardizationNameStandardMapper.insert(standard);
        }
    }

    @Override
    public void updateNameDescByIds(StandardizationNameStandard nameStandard) {
        String ids = nameStandard.getIds();
        if (!ids.contains("_")) {
            nameStandard.setStandardId(Integer.valueOf(ids));
            standardizationNameStandardMapper.updateById(nameStandard);
        }
        if (ids.contains("_")) {
            String[] result = ids.split("_");
            for (String s : result) {
                standardizationNameStandardMapper.deleteById(s);
            }
            String enumName = nameStandard.getEnumName();
            String[] names = enumName.split("、");
            String matchWord = nameStandard.getMatchWord();

            for (String name : names) {
                StandardizationNameStandard standard = new StandardizationNameStandard();
                standard.setEnumName(name);
                standard.setMatchWord(matchWord);
                standardizationNameStandardMapper.insert(standard);
            }
        }
    }

    @Override
    public void DelNameDescByIds(String ids) {
        if (!ids.contains("_")) {
            standardizationNameStandardMapper.deleteById(ids);
        }
        if (ids.contains("_")) {
            String[] result = ids.split("_");
            for (String s : result) {
                standardizationNameStandardMapper.deleteById(s);
            }
        }
    }

    @Override
    public void updateDeviceStandard(Integer problemId, String standardName, String standardDesc) {
        QueryWrapper<StandardizationDeviceStandard> wrapper = new QueryWrapper<>();
        wrapper.eq("standard_name", standardName);
        wrapper.eq("standard_desc", standardDesc);
        List<StandardizationDeviceStandard> deviceStandards = standardizationDeviceStandardMapper.selectList(wrapper);
        for (StandardizationDeviceStandard standard : deviceStandards) {
            Integer standardId = standard.getStandardId();
            StandardizationPoint point = standardizationPointMapper.selectById(problemId);
            point.setStandardId(standardId);
            standardizationPointMapper.updateById(point);
        }
    }

    @Override
    public String train(Integer problemId) {
        StandardizationPoint point = standardizationPointMapper.selectById(problemId);
        Integer isTrain = point.getIsTrain();
        Integer standardId = point.getStandardId();
        if (isTrain == 1) {
            point.setIsTrain(0);
            //取消训练删除时间
            LocalDateTime dateTime = LocalDateTime.of(0, 1, 1, 0, 0, 0, 0);
            point.setTrainTime(dateTime);
            standardizationPointMapper.updateById(point);
            return "已取消训练";
        }
        if (isTrain == 0 && standardId != null) {
            point.setIsTrain(1);
            //更新时间
            point.setTrainTime(LocalDateTime.now());
            standardizationPointMapper.updateById(point);
            return "已训练";
        }
        return "";
    }

    @Override
    public PageResult<StandardizationPointDTO> dailyTraining(Integer page, Integer size, String time, String pointName) {
        QueryWrapper<StandardizationPoint> wrapper = new QueryWrapper<>();
        List<StandardizationPointDTO> pointDTOS = new ArrayList<>();
        wrapper.like("train_time", time);
        wrapper.eq("is_train", 1);
        if (StringUtils.isNotEmpty(pointName)) {
            wrapper.like("point_name", pointName);
        }
        List<StandardizationPoint> list = standardizationPointMapper.selectList(wrapper);
        for (StandardizationPoint s : list) {
            StandardizationPointDTO dto = new StandardizationPointDTO();
            dto.setProblemId(s.getProblemId());
            dto.setPointName(s.getPointName());
            Integer standardId = s.getStandardId();
            if (null != standardId) {
                StandardizationDeviceStandard standard = standardizationDeviceStandardMapper.selectById(standardId);
                dto.setStandardId(standardId);
                dto.setStandardName(standard.getStandardName());
                dto.setStandardDesc(standard.getStandardDesc());
            }
            Integer isTrain = s.getIsTrain();
            if (null != isTrain) {
                dto.setIsTrain(isTrain);
            }
            LocalDateTime trainTime = s.getTrainTime();
            if (null != trainTime) {
                dto.setTrainTime(trainTime);
            }
            pointDTOS.add(dto);
        }
        PageResult<StandardizationPointDTO> result = new PageResult<>();
        List<StandardizationPointDTO> dtoList = pointDTOS.stream().skip((page - 1) * size).limit(size).collect(Collectors.toList());
        result.setList(dtoList);
        result.setTotal((long) pointDTOS.size());
        result.setPage(Long.valueOf(page));
        result.setSize(Long.valueOf(size));
        result.setTotalPages((long) (pointDTOS.size() / size + (pointDTOS.size() % size != 0 ? 1 : 0)));
        return result;
    }

    //23点执行一次
    @Scheduled(cron = "0 0 23 * * ?")
    public void cronAnalysisTimingT0007() {
        log.info("自动分析0007点表");
        this.analysisTimingT0007();
        log.info("自动分析0007点表完成");
    }

    /**
     * 定时分析点表的数据新增或者删除
     */
    @Override
    public void analysisTimingT0007() {
        //先比较厂站
        List<Integer> newIds = t0007PointMapper.selectStationNo();
        List<Integer> oldIds = standardizationPointMapper.selectStationNo();
        for (Integer id : oldIds) {
            if (!newIds.contains(id)) {
                //删除
                QueryWrapper<StandardizationPoint> wrapper = new QueryWrapper<>();
                wrapper.eq("station_no", id);
                standardizationPointMapper.delete(wrapper);
            } else {
                //比较点名
                List<String> newPointNameList = t0007PointMapper.selectPointNameByStationNo(id);
                List<String> oldPointNameList = standardizationPointMapper.selectPointNameByStationNo(id);
                for (String pointName : oldPointNameList) {
                    if (!newPointNameList.contains(pointName)) {
                        //删除
                        QueryWrapper<StandardizationPoint> wrapper = new QueryWrapper<>();
                        wrapper.eq("station_no", id).eq("point_name", pointName);
                        standardizationPointMapper.delete(wrapper);
                    }
                }
                for (String pointName : newPointNameList) {
                    if (!oldPointNameList.contains(pointName)) {
                        StandardizationPoint point = new StandardizationPoint();
                        //排除备用1，备用2，DO_JS.JS_2971_1737，这种点名
                        if (!pointName.matches("^备用.*$") && pointName.matches("^.*[\\u4e00-\\u9fa5]+.*$")) {
                            point.setPointName(pointName);
                            point.setStationNo(id);
                            QueryWrapper<T0003Station> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("C0003_STATION_NO", id);
                            T0003Station station = t0003StationMapper.selectOne(queryWrapper);
                            point.setStation(station.getC0003StationDesc());
                            //更新时间
                            Date date = new Date();
                            // 将 Date 转换为 Instant
                            Instant instant = date.toInstant();
                            // 将 Instant 转换为 LocalDateTime
                            LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                            point.setRecordTime(localDateTime);
                            point.setCreateTime(localDateTime);
                            point.setIsTrain(0);
                            standardizationPointMapper.insert(point);
                        }
                    }
                }
            }
        }
        for (Integer id : newIds) {
            if (!oldIds.contains(id)) {
                //新增
                List<String> pointNameList = t0007PointMapper.selectPointNameByStationNo(id);
                for (String pointName : pointNameList) {
                    StandardizationPoint point = new StandardizationPoint();
                    //排除备用1，备用2，DO_JS.JS_2971_1737，这种点名
                    if (!pointName.matches("^备用.*$") && pointName.matches("^.*[\\u4e00-\\u9fa5]+.*$")) {
                        point.setPointName(pointName);
                        point.setStationNo(id);
                        QueryWrapper<T0003Station> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("C0003_STATION_NO", id);
                        T0003Station station = t0003StationMapper.selectOne(queryWrapper);
                        point.setStation(station.getC0003StationDesc());
                        //更新时间
                        Date date = new Date();
                        // 将 Date 转换为 Instant
                        Instant instant = date.toInstant();
                        // 将 Instant 转换为 LocalDateTime
                        LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                        point.setRecordTime(localDateTime);
                        point.setCreateTime(localDateTime);
                        point.setIsTrain(0);
                        standardizationPointMapper.insert(point);
                    }
                }
            }
        }
    }

    @Override
    public void analysisT0007(Integer C0007_POINT_ID) {
        List<Integer> staIds = t0007PointMapper.selectStationNo();
        // 使用 Collections.sort() 方法进行排序
        //Collections.sort(staIds);
        for (Integer stationNo : staIds) {
            List<String> pointNameList = t0007PointMapper.selectPointNameByStationNo(stationNo);
            for (String pointName : pointNameList) {
                StandardizationPoint point = new StandardizationPoint();
                //排除备用1，备用2，DO_JS.JS_2971_1737，这种点名
                if (!pointName.matches("^备用.*$") && pointName.matches("^.*[\\u4e00-\\u9fa5]+.*$")) {
                    point.setPointName(pointName);
                    point.setStationNo(stationNo);
                    QueryWrapper<T0003Station> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("C0003_STATION_NO", stationNo);
                    T0003Station station = t0003StationMapper.selectOne(queryWrapper);
                    //point.setStation(t0003StationMapper.selectById(stationNo).getC0003StationDesc());
                    //t0003StationMapper.
                    point.setStation(station.getC0003StationDesc());
                    //更新时间
                    Date date = new Date();
                    // 将 Date 转换为 Instant
                    Instant instant = date.toInstant();
                    // 将 Instant 转换为 LocalDateTime
                    LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                    point.setRecordTime(localDateTime);
                    point.setCreateTime(localDateTime);
                    point.setIsTrain(0);
                    standardizationPointMapper.insert(point);
                }
            }
        }
    }

    @Override
    public void updateValidResult(Integer problemId, String validResult) {
        StandardizationPoint point = standardizationPointMapper.selectById(problemId);
        if (validResult.equals("合格")) {
            point.setValidResult(1);
        }
        if (validResult.equals("不合格")) {
            point.setValidResult(0);
        }
        //更新时间
        Date date = new Date();
        // 将 Date 转换为 Instant
        Instant instant = date.toInstant();
        // 将 Instant 转换为 LocalDateTime
        LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();

        point.setRecordTime(localDateTime);
        standardizationPointMapper.updateById(point);
    }

    public void ModelAnalysisTiming() throws IllegalAccessException {
        List<StandardizationPoint> pointList = standardizationPointMapper.selectStandardIdNull();
        for (StandardizationPoint point : pointList) {
                String pointName = point.getPointName();
                RestTemplate restTemplate = new RestTemplate();
                // 发送 POST 请求
                Map<String, Object> requestBody = new HashMap<>();
                //requestBody.put("query", "220KV母线变压器闭合");
                requestBody.put("query", pointName);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                // 将请求体转换成字符串形式
                String jsonBody = JSONObject.toJSONString(requestBody);
                HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);
                ResponseEntity<Object> entity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Object.class);
                Object body = entity.getBody();
                //获取属性名
                Field[] fields = body.getClass().getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    String value = field.get(body).toString();
                    if (value.contains("result")) {
                        String[] keyValuePairs = value.substring(value.indexOf("{") + 1, value.indexOf("}")).split(", ");
                        Map<String, String> keyValueMap = new HashMap<>();
                        for (String pair : keyValuePairs) {
                            String[] splitPair = pair.split("=");
                            keyValueMap.put(splitPair[0].trim(), splitPair[1].trim());
                        }
                        //String deviceType = keyValueMap.get("device_type");
                        String checkRule = keyValueMap.get("standard_desc");
                        //String deviceName = keyValueMap.get("device_name");
                        String infoName = keyValueMap.get("info_name");
                        Double proba = Double.valueOf(keyValueMap.get("proba"));
                        String standardAction = keyValueMap.get("standard_action");
                        String standardDesc = keyValueMap.get("standard_desc");
                        String standardId = keyValueMap.get("standard_id");
                        String standardName = keyValueMap.get("standard_name");
                        Integer stationMerge = Integer.valueOf(keyValueMap.get("station_merge"));
                        if (StringUtils.isNotEmpty(infoName)){
                            point.setInformationType(infoName);
                        }
                        if (StringUtils.isNotEmpty(standardAction)){
                            point.setActionName(standardAction);
                        }
                        if (StringUtils.isNotEmpty(checkRule)){
                            point.setCheckRules(checkRule);
                        }
                        if (null != proba){
                            point.setSimilarity(proba);
                        }
                        if (proba > 0.8) {
                            point.setValidResult(1);
                            point.setValidResultStr("合格");
                        } else {
                            point.setValidResult(0);
                            point.setValidResultStr("不合格");
                        }

                        if (null != stationMerge) {
                            point.setMainMerge(stationMerge);
                        }
                        if (!StringUtils.isEmpty(standardId)) {
                            point.setStandardId(Integer.valueOf(standardId));
                        }
                        if (!StringUtils.isEmpty(standardDesc)) {
                            point.setStandardDesc(standardDesc);
                        }
                        if (!StringUtils.isEmpty(standardName)) {
                            point.setStandardName(standardName);
                        }
                    }
                }
                point.setIsTrain(0);
                //更新时间
                Date date = new Date();
                // 将 Date 转换为 Instant
                Instant instant = date.toInstant();
                // 将 Instant 转换为 LocalDateTime
                LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                point.setRecordTime(localDateTime);
                standardizationPointMapper.updateById(point);
            //}
        }
        log.info("信号标准化分析完成");
    }

    //每天5点执行一次
    @Scheduled(cron = "0 0 5 * * ?")
    public void cronModelAnalysisTiming() throws IllegalAccessException {
        log.info("自动模型分析");
        this.ModelAnalysisTiming();
        log.info("模型分析完成");
    }
}